package cn.com.util;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.ws.commons.util.Base64;
import org.springframework.web.multipart.MultipartFile;

//import Decoder.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;

public class ImageUtils {

	public static String IMAGE_ROOT = "/upai_resources";

	// 获取上传的图片路径 //
	// D:\Software\apache-tomcat-7.0.52\webapps\webmvc/../xx_resources
	public static String getServletWebAppsPath(HttpServletRequest request) {
		String realpath = request.getSession().getServletContext()
				.getRealPath("");
		realpath = realpath.replace("\\", "/");
		// realpath= realpath.replace("uthink-backstage","");
		return realpath;
	}

	public static String getResourcesPath(HttpServletRequest request) {
		String realpath = request.getSession().getServletContext()
				.getRealPath("");
		realpath = realpath.replace("\\", "/");
		realpath = realpath.replace(request.getSession().getServletContext()
				.getContextPath(), ImageUtils.IMAGE_ROOT);
		return realpath;
	}

	// 获取存储图片的路径
	public static String getDataBaseImagePath() {
		String filePath = "";
		return filePath;
	}

	/**
	 * 图片转化成base64字符串
	 * 
	 * @param imgFilePath
	 *            , eg: "d://test.jpg"
	 */
	public static String ImageGetBase64Str(String imgFilePath) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
																// String
																// imgFile =
																// "d://test.jpg";//待处理的图片
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(imgFilePath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		return Base64.encode(data); // 返回Base64编码过的字节数组字符串
	}

	/**
	 * base64字符串转化成图片
	 * 
	 * @param imgBase64Str
	 * @param imgFilePath
	 *            , eg: "d://222.jpg"
	 */
	public static boolean ImageGenerateFromBase64Str(String imgBase64Str,
			String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
		if (imgBase64Str == null) // 图像数据为空
			return false;
		try {
			// Base64解码
			byte[] b = Base64.decode(imgBase64Str);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			// 生成jpeg图片
			// String imgFilePath = "d://222.jpg";//新生成的图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean GenerateImage(String imgStr, String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null) // 图像数据为空
			return false;
		// BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码

			// byte[] b = decoder.decodeBuffer(imgStr);
			byte[] b = Base64Util.decode(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			// 生成jpeg图片
			// String imgFilePath = "C:/Users/Star/Desktop/test22.png";// 新生成的图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 上传文件并返回相对路径
	 * 
	 * @param request
	 * @param fold
	 *            文件夹 （开头和结尾都必须以/开始和结束）
	 * @param file
	 *            文件
	 * @return
	 * @throws Exception
	 */
	public static String uploadFile(HttpServletRequest request, String fold,
			MultipartFile file) throws Exception {

		String url = "";
		String path = getResourcesPath(request) + fold;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String sdfStr = sdf.format(new Date());
		// 文件真实名称
		String realname = file.getOriginalFilename();
		String fileName = sdfStr + UUIDUtil.generateString(4)
				+ realname.substring(realname.lastIndexOf("."));
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		// 保存
		file.transferTo(targetFile);
		url = ImageUtils.IMAGE_ROOT + fold + fileName;
		return url;
	}

}
